package com.base.myproject.server;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jbpm.api.TaskService;

import com.base.myproject.client.Connector.ConnectorObject;
import com.base.myproject.client.Connector.ConnectorObjectContainer;
import com.base.myproject.client.busi.AddItem;
import com.base.myproject.client.busi.BO.BaseObject;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.ModelDataList;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.busi.ClientEnv.SyncObjectContainer;
import com.base.myproject.client.busi.b2c.CcodeObject;
import com.base.myproject.client.busi.b2c.shopping.ShopCartObject;
import com.base.myproject.client.busi.service.Associator;
import com.base.myproject.client.busi.service.AssociatorX;
import com.base.myproject.client.busi.service.PayItem;
import com.base.myproject.client.busi.system.BcodeSync;
import com.base.myproject.client.busi.system.PrinterSync;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Status;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.client.tools.CommandBcodePermission;
import com.base.myproject.client.tools.CommandHtmlTable;
import com.base.myproject.client.tools.CommandPrepareCall;
import com.base.myproject.client.tools.CommandSync;
import com.base.myproject.client.tools.CommandSyncAssociator;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncCopyUP;
import com.base.myproject.client.tools.CommandSyncExeSql;
import com.base.myproject.client.tools.CommandSyncGetModelDatas;
import com.base.myproject.client.tools.CommandSyncHasCcode;
import com.base.myproject.client.tools.CommandSyncHasCcodeNotPass;
import com.base.myproject.client.tools.CommandSyncLastStoreg;
import com.base.myproject.client.tools.CommandSyncMakeCode;
import com.base.myproject.client.tools.CommandSyncPay;
import com.base.myproject.client.tools.CommandSyncRatify;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncStartFlow;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.Item;
import com.base.myproject.client.ui.codenamemap.CodeNameMap;
import com.base.myproject.server.Comet.CometContainer;
import com.base.myproject.server.database.MakeCode;
import com.base.myproject.server.database.PoolMan;
import com.base.myproject.server.init.MyLogger;
import com.base.myproject.server.jbpm.WorkFlow;
import com.base.myproject.server.tools.DataSetTool;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	public String greetServer(String[][] name, String type) {
		//System.out.println("name=" + name.length);
		// for(int i=0;i<name.length;i++)
		// {
		// for(int j=0;j<name[i].length;j++)
		// {
		// System.out.println(name[i][j]);
		// }
		// }
		//		
		PoolMan pm = new PoolMan();
		Vector v = new Vector();

		for (int i = 0; i < name[0].length; i++) {

			for (int j = 0; j < name[1].length; j++) {
				String sql = "insert into menupermissions (groupicode,menucode) values('"
						+ name[0][i] + "','" + name[1][j] + "')";
				//System.out.println(sql);
				v.add(sql);
			}
		}
		v
				.add("delete menupermissions where icode not in(select max(icode) as icode  from menupermissions group by menucode,groupicode)");
		try {
			pm.getPool("test");
			pm.handleTransaction(v);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "false";
		}
		return "success";
	}

	public String[][] greetServerarr(String name) {

		try {
			return getMenu();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	static String[][] strarr = new String[][] { { "1", "zz", "zz" },
			{ "1001", "zgw", "zz" }, { "10010001", "zgw01", "zz" },
			{ "10010002", "zgw01", "zz" }, { "10020001", "zgw01", "zz" },

	};

	public String[][] getMenu() throws Exception {
		PoolMan pm = new PoolMan();

		String rowsql = "select count(*) as rownum from menu";
		ResultSet rowrs = pm.executeQuery(rowsql);
		rowrs.next();
		int rownum = rowrs.getInt("rownum");

		String[][] strarr = new String[rownum][];
		String sql = "select menucode,menuname from menu order by menucode";
		ResultSet rs = pm.executeQuery(sql);
		int row = 0;
		while (rs.next()) {
			strarr[row] = new String[] { rs.getString("menucode"),
					rs.getString("menuname") };
			row++;

		}
		return strarr;
	}

	/*
	 * public static TreeModel get123() { TreeModel r = new TreeModel("root");
	 * java.util.Map<String, TreeModel> h = new java.util.HashMap<String,
	 * TreeModel>(); for(int i=0;i<strarr.length;i++) {
	 * if(strarr[i][0].length()!=8) { TreeModel ttemp = new
	 * TreeModel(strarr[i][1]); h.put(strarr[i][0].length()/4+"", ttemp);
	 * if(strarr[i][0].length()/4!=0) { h.get((strarr[i][0].length()/4 -
	 * 1)+"").add(ttemp); } else { r.add(ttemp); } } else { Music mtemp = new
	 * Music(strarr[i][0],strarr[i][1],strarr[i][2]);
	 * h.get((strarr[i][0].length()/4 - 1)+"").add(mtemp); } }
	 * 
	 * return r;
	 * 
	 * }
	 */
	/**
	 * 用户ccode提交购物车 购物车提交后将保存到订单里，旧的订单将被删除 在这些操作之前，要做数据的完整性进行校验。
	 */
	@Override
	public String greetServerShoppingCart(LinkedList<ShopCartObject> ll,
			String ccode) {
		// TODO Auto-generated method stub
		System.out.println("server size=" + ll.size());
		System.out.println("ccode = " + ccode);
		String message = "";
		Date d = new Date();
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		java.text.SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
		String datestr = sdf.format(d);
		String ordercode = sdf2.format(d);
		int inccode = MakeCode.makeCode("b2clistorder", "ordercode", 8, 5);
		ordercode += inccode;
		PoolMan pm = new PoolMan();
		Vector<String> v = new Vector<String>();
		double subtotal = 0.00;
		for (ShopCartObject sco : ll) {
			System.out.println(sco.getTotle());
			if (!sco.check()) {
				System.out.println("有错误，购物车商品录入有不完整的记录");
			}
			String price = sco.getPrice();
			String discountprice = sco.getDiscountprice();
			// 如果discountprice（折扣价）存在那么就取折扣价，否则用原价。
			String finalprice;

			double total;

			finalprice = sco.getFinalprice();
			total = Double.parseDouble(finalprice)
					* Double.parseDouble((sco.getQty() == null || sco.getQty()
							.equals("")) ? "0" : sco.getQty());
			BigDecimal b = new BigDecimal(total);
			total = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			String str = " insert into b2clistorderg (b2cgcode,b2cgname,gcode,gname,orderdate,qty,finalprice,totle,bcode,bname,ccode,ordercode) values (";
			str += " '" + sco.getB2cgcode() + "'" + ",'" + sco.getB2cgname()
					+ "'" + ",'" + sco.getGcode() + "'" + ",'" + sco.getGname()
					+ "'" + ",'" + datestr + "'" + ",'" + sco.getQty() + "'"
					+ ",'" + finalprice + "'" + ",'" + total + "'" + ",'"
					+ sco.getBcode() + "'" + ",'" + sco.getBname() + "'" + ",'"
					+ ccode + "'" + ",'" + ordercode + "')";

			System.out.println(str);
			v.add(str);
			subtotal = subtotal + total;
		}

		String str = "insert into b2clistorder (ordercode,ccode,orderdate,status,totalmoney) values (";
		str += "'" + ordercode + "','" + ccode + "','" + datestr + "','"
				+ Status.XIADAN + "','" + subtotal + "')";
		v.add(str);
		String deletecar = "delete b2cshopcar where ccode ='" + ccode + "'";
		v.add(deletecar);
		try {
			pm.getPool("test");
			pm.handleTransaction(v);
		} catch (Exception e) {
			
			e.printStackTrace();
		} finally {
			try {
				pm.close("test");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "success";
	}

	@Override
	public String greetServerCcode(CcodeObject cco) {
		// TODO Auto-generated method stub
		System.out.println("ccode" + cco.getSaveSql());
		PoolMan pm = new PoolMan();
		try {
			pm.Update(cco.getSaveSql());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				pm.close("test");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			;
		}
		return SystemMessage.getMessage(4, 0);
	}

	// @Override
	public LinkedList<BaseObject> getBaseObject(String querysql,
			String classname) {

		LinkedList ll = new LinkedList();
		try {
			Class c = Class.forName(classname);

			Object bo = c.newInstance();
			if (bo instanceof BaseObject) {
				System.out.println("is bo");
				for (int i = 0; i < 10; i++) {
					Object bo2 = c.newInstance();

					((BaseObject) bo2).set("b2cgcode", "zgw" + i);
					((BaseObject) bo2).set("icode", i + "");
					((BaseObject) bo2).set("shoppingdate", "---------------");
					((BaseObject) bo2).setBusistatus(0);
					ll.add(bo2);
				}
				return ll;
			} else {
				System.out.println("is not bo");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("00");
		return null;
	}

	/**
	 * 提交baseobject保存
	 */
	@Override
	public String saveBaseObject(Vector<String> savevector,
			HashMap<String, String> params) {
		PoolMan pm = new PoolMan();
		String message = SystemMessage.getMessage(4, 1);
		try {
			pm.getPool("test");
			if (pm.handleTransactionX(savevector)) {
				message = SystemMessage.getMessage(4, 0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// message = SystemMessage.getMessage(4, 1);
			message += e.getMessage();
			//e.printStackTrace();
			

		} finally {
			try {
				pm.close("test");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				// message = SystemMessage.getMessage(4, 1);
				message += e.getMessage();
				//e.printStackTrace();
			}
			;
		}
		// message = SystemMessage.getMessage(4, 0);
		return message;

	}

	/**
	 * mode 1 为根据ccode查找 2 为根据name查找 3 为根据phone查找 4 为根据s_cardno查找
	 * 
	 * @see
	 * com.base.myproject.client.tools.GreetingService#getAssociator(java.lang
	 * .String, int)
	 */
	@Override
	public AssociatorX getAssociatorx(String code, int mode) {
		AssociatorX associtorx = new AssociatorX();
		String sql ="";
		sql = "select a.ccode,a.cname,a.s_mobil,a.viplevel,a.s_cardno from ";
		sql += "( ";
		if (mode == 2) {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno from ccode where cname ='"
					+ code + "'  ";
		} else if (mode == 3) {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where s_mobil ='"
					+ code + "'  ";
		} else if (mode == 4) {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where s_cardno ='"
					+ code + "'  ";
		} else {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where ccode ='"
					+ code + "'  ";
		}

		sql += ") as a ";
		
		
		PoolMan pm = new PoolMan();
		try {
			ResultSet rs = pm.executeQuery(sql);
			if (rs.next()) {
				associtorx.setCcode(rs.getString("ccode"));
				associtorx.setS_cardno(rs.getString("s_cardno"));
				
				associtorx.setName(rs.getString("cname"));
				associtorx.setMobil(rs.getString("s_mobil"));
				
			
			}
		}catch (Exception e) {
			
			e.printStackTrace();
		}
		
		//获得账户交易记录
		String findsql ="select sqlvalue  from sqltable where name='s_finace_acc'";
		
		
		
		
//		str =str.replaceAll(Pattern.quote("{SALARYITEM}"), salaryitemmacro);
//		str = str.replaceAll(Pattern.quote("{BCODE}"), bcodemacro);

		
		String paysql = "";
	
		try {
			ResultSet rs = pm.executeQuery(findsql);
			rs.next();
			paysql = rs.getString("sqlvalue");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		

		paysql =paysql.replaceAll(Pattern.quote("{SCARDNO}"), associtorx.getS_cardno());
		System.out.println(paysql);
		
		List<PayItem> paylist = new LinkedList<PayItem>();
		try {
			ResultSet rs = pm.executeQuery(paysql);
			
			while(rs.next())
			{
				PayItem pi =new PayItem();
				pi.setAccountname(rs.getString("name"));
				pi.setLastamount(rs.getDouble("lastamount"));
				
				paylist.add(pi);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		associtorx.setPaylist(paylist);
		return associtorx;
	}
	/**
	 * mode 1 为根据ccode查找 2 为根据name查找 3 为根据phone查找 4 为根据s_cardno查找
	 * 
	 * @see
	 * com.base.myproject.client.tools.GreetingService#getAssociator(java.lang
	 * .String, int)
	 */
	@Override
	public Associator getAssociator(String code, int mode) {
		// TODO Auto-generated method stub
		Associator associtor = new Associator();
		associtor.setFinance(0);
		String sql = associtor.getSql();
		// sql =
		// "select sum(finance*dc) as finance from s_service_finance where ccode='"+ccode+"' group by ccode";

		sql = "select a.ccode,a.cname,a.s_mobil,a.viplevel,a.s_cardno,b.finance -isnull(c.paid,0)  as finance,isnull(d.jifen,0) as jifen from ";
		sql += "( ";
		if (mode == 2) {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno from ccode where cname ='"
					+ code + "'  ";
		} else if (mode == 3) {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where s_mobil ='"
					+ code + "'  ";
		} else if (mode == 4) {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where s_cardno ='"
					+ code + "'  ";
		} else {
			sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where ccode ='"
					+ code + "'  ";
		}

		sql += ") as a ";

		sql += "		left join ";

		sql += "( ";
		sql += "select sum(isnull(finance*dc,0)) as finance,ccode,max(updatedate) updatedate from s_service_finance group by ccode ";
		sql += ") as b ";

		sql += "on a.ccode = b.ccode ";
		sql += " left join ";
		sql += "( ";
		sql += "select sum(isnull(paid,0)) as paid,ccode from s_service_po where   busistatus=524288 group by ccode ";
		sql += ") as c ";
		sql += "on a.ccode = c.ccode";

		sql += " left join  ";

		sql += "		( ";
		sql += "select sum(isnull(finance,0)) as jifen ,ccode from s_service_finance where dc = 1 group by ccode ";
		sql += ")  ";
		sql += "as d ";
		sql += "on a.ccode = d.ccode";

		PoolMan pm = new PoolMan();
		try {
			ResultSet rs = pm.executeQuery(sql);
			if (rs.next()) {
				associtor.setCcode(rs.getString("ccode"));
				associtor.setS_cardno(rs.getString("s_cardno"));
				associtor.setFinance(rs.getDouble("finance"));
				associtor.setName(rs.getString("cname"));
				associtor.setPhone(rs.getString("s_mobil"));
				associtor.setJifen(rs.getDouble("jifen"));
				associtor.setType(rs.getString("viplevel"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return associtor;
	}

	@Override
	public CodeNameMap getCodeNameMap(CodeNameMap cnm) {
		// TODO Auto-generated method stub
		// System.out.println(cnm.getClass());

		// CodeNameMap aa = new CodeNameMap ();
		HashMap<String, String> hm = new HashMap<String, String>();
		PoolMan pm = new PoolMan();
		String key = "";
		String value = "";

		try {
			System.out.println("sql = " + cnm.getLoadSql());
			ResultSet rs = pm.executeQuery(cnm.getLoadSql());
			while (rs.next()) {
				key = rs.getString(1);
				value = rs.getString(2);
				if (key != null && value != null) {
					hm.put(rs.getString(1), rs.getString(2));
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		cnm.setHashTable(hm);
		return cnm;
	}

	/*
	 * @Override public String saveBaseObject(LinkedList<BaseObject> bolinklist,
	 * String method) {
	 * 
	 * return null; }
	 */

	public String getbnamebyshortname(String shortcode) {
		// String str[] =new String[2];
		String str = "";
		PoolMan pm = new PoolMan();
		String sql = "select bcode,bname from  bcode where bcodeshortcode = '"
				+ shortcode + "'";
		ResultSet rs;
		try {
			rs = pm.executeQuery(sql);

			if (rs.next()) {
				// str[0] = rs.getString("bcode");
				// str[1] = rs.getString("bname");
				str = rs.getString("bname");
			}
			rs.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} finally {
			try {
				pm.close("test");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return str;
	}

	@Override
	public BcodeSync getBcode(String column, String value) {
		BcodeSync bcodesync = new BcodeSync();

		PoolMan pm = new PoolMan();
		String sql = "select * from  bcode where " + column + " = '" + value
				+ "'";
		ResultSet rs;
		try {
			rs = pm.executeQuery(sql);

			if (rs.next()) {
				bcodesync.setBcode(rs.getString("bcode"));
				bcodesync.setBname(rs.getString("bname"));
				bcodesync.setDepartments(rs.getString("departments"));
				bcodesync.setPassword(rs.getString("password"));
				bcodesync.setEmail(rs.getString("email"));
				bcodesync.setSex(rs.getString("sex"));
				bcodesync.setEdu(rs.getString("edu"));
				bcodesync.setBird(rs.getString("bird"));

				bcodesync.setMobil(rs.getString("mobil"));

				bcodesync.setLiveaddr(rs.getString("liveaddr"));
				bcodesync.setSystemid(rs.getString("systemid"));
				bcodesync.setBcodeshortcode(rs.getString("bcodeshortcode"));
			}
			rs.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} finally {
			try {
				pm.close("test");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return bcodesync;
	}
	
	public DataSet getTasks(String bcode) {
		WorkFlow jbpm = new WorkFlow();
		
		List<org.jbpm.api.task.Task> list = jbpm.findPersonalTasks(bcode);
		TaskService taskService = jbpm.getTaskService();
		String sql = "select * from hr_Attendance_ot where icode in (";
		for (org.jbpm.api.task.Task task : list) {
			sql += taskService.getVariable(task.getId(), "icode").toString() + ",";
		}
		sql = sql.substring(0, sql.length()-1) + ")";
		return getDataSet(sql);
	}

	@Override
	public DataSet getDataSet(String sql) {

	/*	java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
		//String datestr = sdf.format(d );
		PoolMan pm = new PoolMan();
		// String sql =
		// "select bcode,bname from  bcode where bcode is not null and bname is not null";
		ResultSet rs = null;
		DataSet dataset = new DataSet();
		try {
			rs = pm.executeQuery(sql);

			int columncount = rs.getMetaData().getColumnCount();
			String[] column_names = new String[columncount];
			for (int i = 0; i < columncount; i++) {
				column_names[i] = rs.getMetaData().getColumnName(i + 1);
			}
			
			while (rs.next()) {
				Row row = new Row();
				for (int j = 0; j < columncount; j++) {
					Cell c = new Cell();
					c.setCellname(column_names[j]);
				//	System.out.println(column_names[j]+" == "+rs.getMetaData().getColumnType(j+1));
					//日期
					if(rs.getMetaData().getColumnType(j+1)==java.sql.Types.TIMESTAMP)
					{
						if(rs.getTimestamp(column_names[j])!=null)
						{
						String datestr = sdf.format(rs.getTimestamp(column_names[j]));
						c.setValue(datestr);
						}
						else
						{
							c.setValue(null);
						}
					}
					else
					{
					c.setValue(rs.getString(column_names[j]));
					}
					
					row.addCell(c);
				}
				dataset.addRow(row);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
				pm.close("test");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return dataset;*/
		DataSetTool DST = new DataSetTool();
		return DST.getDataSet(sql);
	}

	@Override
	public String getPrinterHtml(PrinterSync printersync) {
		String printcode = printersync.getPrintcode();
		if (printcode.equals("service_1001")) {
			return getservice_add_finance(printersync,1);
		}
		if (printcode.equals("service_1002")) {
			return getservice_add_finance(printersync,2);
		}
		if (printcode.equals("service_1003")) {
			return printassociate (printersync);
		}
	
		return "未找到打印信息";
	}
/**
 * 
 * @param printersync
 * @param mode 1 根据ccode 的icode查找，2 根据 卡号进行查找
 * @return
 */
	String getservice_add_finance(PrinterSync printersync,int mode) {
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String Systeminfo = "";
		// 改操作员的公司信息
		String systeminfosql = " ";

		systeminfosql += "select * from ";
		systeminfosql += " ( ";
		systeminfosql += " select bcode,bname ,systemid from bcode where bcode = '"
				+ printersync.getBcode() + "' ";
		systeminfosql += " ) as a ";
		systeminfosql += " left join ";
		systeminfosql += " ( ";
		systeminfosql += " select * from systeminfo where exists (select * from bcode where bcode.systemid = systeminfo.id and bcode = '"
				+ printersync.getBcode() + "') ";
		systeminfosql += " ) as b ";
		systeminfosql += " on a.systemid = b.id ";
		
		// 会员最后一次充值的信息
		String financesql="";
		if(mode==1)
		{
		 financesql = "select a.ccode,a.cname,a.s_cardno,b.updatedate,b.finance,b.finance_real,b.finance_gif,(select bname from bcode where bcode.bcode =b.bcode) as bname from  ";
		financesql += " ( ";
		financesql += " select * from ccode where icode = '"
				+ printersync.getIcode() + "' ";
		financesql += " ) as a ";
		financesql += " left join  ";
		financesql += " ( ";
		financesql += " select top 1 * from s_service_finance where exists(select * from ccode where ccode.ccode= s_service_finance.ccode and ccode.icode = '"
				+ printersync.getIcode() + "') order by updatedate desc ";
		financesql += " ) as b  on a.ccode = b.ccode ";

		}
		else if(mode==2)
		{
			 financesql = "select a.ccode,a.cname,a.s_cardno,b.updatedate,b.finance ,b.finance_real,b.finance_gif,(select bname from bcode where bcode.bcode =b.bcode) as bname from  ";
				financesql += " ( ";
				financesql += " select * from ccode where s_cardno = '"
						+ printersync.getIcode() + "' ";
				financesql += " ) as a ";
				financesql += " left join  ";
				financesql += " ( ";
				financesql += " select top 1 * from s_service_finance where exists(select * from ccode where ccode.ccode= s_service_finance.ccode and ccode.s_cardno = '"
						+ printersync.getIcode() + "') order by updatedate desc ";
				financesql += " ) as b  on a.ccode = b.ccode ";

		}
		PoolMan pm = new PoolMan();

		ResultSet systeminfors = null;
		ResultSet financers = null;

		String system_name = "";
		String system_title = "";
		String system_tel = "";
		String system_fax = "";
		String system_printmessage = "";
		String system_addr = "";
		String system_slogan = "";
		String system_zip = "";
		String bname = "";
		try {
			systeminfors = pm.executeQuery(systeminfosql);
			if (systeminfors.next()) {
				system_name = systeminfors.getString("name");
				system_title = systeminfors.getString("title");
				system_tel = systeminfors.getString("tel");
				system_fax = systeminfors.getString("fax");
				system_printmessage = systeminfors.getString("printmessage");
				system_addr = systeminfors.getString("addr");
				system_slogan = systeminfors.getString("slogan");
				system_zip = systeminfors.getString("zip");
				bname = systeminfors.getString("bname");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (systeminfors != null) {
				try {
					systeminfors.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		String finance_cname = "";
		String finance_s_cardno = "";
		String finance_updatedate = "";
		String finance_finance = "";
		String finance_bname = "";
		Double finance_real = 0.00;
		Double finance_gif = 0.00;
		try {
			financers = pm.executeQuery(financesql);
			if (financers.next()) {
				finance_cname = financers.getString("cname");
				finance_s_cardno = financers.getString("s_cardno");
				finance_updatedate = financers.getString("updatedate");
				finance_finance = financers.getString("finance");
				finance_real = financers.getDouble("finance_real");
				finance_gif = financers.getDouble("finance_gif");
				finance_bname = financers.getString("bname");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (financers != null) {
				try {
					financers.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		Associator assoc=null;
		if(finance_s_cardno!=null)
		{
			 assoc=getAssociator(finance_s_cardno,4);
		}
		String str = "";
		str += "<table cellpadding='3'>";
		str += "<tr>";
		str += "<td colspan='2' align='center'><span><U><strong>"
				+ system_title + "</strong></U></span></td>";
		str += "</tr>";
		str += "<tr> ";
		str += "<td width='100'><span>卡号:</span>" + finance_s_cardno + "</td>";
		str += "<td><span>顾客:</span>" + finance_cname + "</td>";
		str += "</tr>";
		str += "<tr> ";
		str += "<td colspan='2' align='left'><span>会员卡余额:</span>"+(assoc==null?"未知":assoc.getFinance())+"</td>";
		str += "</tr>";
		str += "<tr> ";
		str += "<td colspan='2'><span>打印时间:</span><span class='dateFormat'>"
				+ sdf.format(new Date()) + "</span></td>";
		str += "</tr>";
		str += "<tr> ";
		str += "<td colspan='2'><span>操作员:</span><span >" + finance_bname
				+ "</span></td> ";
		str += "</tr>";
		str += "<tr> ";
		str += "<td colspan='2'> ";
		str += "<table class='tblprice'> ";
		str += "<tr style=''>";

		str += "<td ><span>最后充值日期：</span><span >" + finance_updatedate
				+ "</span></td> ";

		str += "</tr>";
		
		if(!(finance_gif==null || finance_gif<1 ))
		{
		str += "<tr style=''>";
		str += "<td ><span>最后充值金额：</span><span >" + finance_real
				+ "</span></td> ";
		str += "</tr>";
		str += "<tr style=''>";
		str += "<td ><span>最后充值赠送金额：</span><span >" + finance_gif
				+ "</span></td> ";
		str += "</tr>";
		}
		
		str += "<tr style=''>";
		str += "<td ><span>最后充值总金额：</span><span >" + finance_finance
				+ "</span></td> ";
		str += "</tr>";
		str += "</table>";
		str += "</td>";
		str += "</tr>";

		str += "<tr> ";
		str += "<td colspan='2' align='left'><span>" + system_name
				+ "</span></td>";
		str += "</tr>";
		str += "<tr> ";
		str += "<td colspan='2' align='left' ><span>电话:</span>" + system_tel
				+ "</td>";
		str += "</tr>";
		str += "<tr> ";
		str += "<td colspan='2' align='center'><span>" + system_slogan
				+ "</span></td> ";
		str += "</tr>";
		str += "</table>";
		return str;

	}

@Override
public ConnectorObjectContainer getConnectorObject() {
	ConnectorObject co = new ConnectorObject();
	co.setHtmlstr("<a><u>asfd111</u></a>");
	co.setXpos(100);
	co.setYpos(20);
	ConnectorObject co2 = new ConnectorObject();
	co2.setHtmlstr("<a><u>asfd222</u></a>");
	co2.setXpos(100);
	co2.setYpos(90);
	
	ConnectorObject co3 = new ConnectorObject();
	co3.setHtmlstr("<a><u>asfd222</u></a>");
	co3.setXpos(50);
	co3.setYpos(90);
	ConnectorObjectContainer coc = new ConnectorObjectContainer();
	coc.addConnectorObject(co);
	coc.addConnectorObject(co2);
	coc.putCOconnect(co, co2);
	coc.putCOconnect(co2, co3);
	coc.putCOconnect(co, co3);
	
	for(int i=0;i<1;i++)
	{
		ConnectorObject co4 = new ConnectorObject();
		co4.setHtmlstr("<a><u>asfd222+"+i+"</u></a>");
		co4.setXpos(1+i);
		co4.setYpos(90);
		coc.putCOconnect(co4, co);
	}
		return coc;
//	return null;
}
/**
 * 打印交接单
 * @return
 */
String printassociate (PrinterSync printersync){
	java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	java.text.SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
	
	String sql = "SELECT sum(paid) as paid FROM s_service_po WHERE datediff(day,serviceenddate,getdate())=0 and  bcode='"+printersync.getBcode()+"'";
	 
	PoolMan pm = new PoolMan();

	ResultSet systeminfors = null;


	String paid = "";
	try {
		systeminfors = pm.executeQuery(sql);
		if (systeminfors.next()) {
//			icode = systeminfors.getString("icode");
//			serviceenddate= systeminfors.getDate("serviceenddate");
			paid = systeminfors.getString("paid");
			
		}

	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		if (systeminfors != null) {
			try {
				systeminfors.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	String str = "";

	str += "<table width='250' cellpadding='3' style=\"font:12px/1.5 Arial, sans-serif;border-collapse:collapse;border-spacing:0\">";
	
	str += "<tr>";
	str += "<td align='center'><span><U><strong>收银交接单</strong></U></span></td>";
	str += "</tr>";
	
	str += "<tr>";
	str += "<td><span>营业日期:</span>"+ sdf1.format(new Date()) +"</td>";
	str += "</tr>";
	
	str += "<tr> ";
	str += "<td><span>交班日期:</span>"+ sdf.format(new Date()) +"</td>";
	str += "</tr>";
	
	str += "<tr> ";
	str += "<td><span>营业收入:</span>"+paid+"</td>";
	str += "</tr>";
	
	str += "<tr> ";
	str += "<td><span>交班人:</span></td>";
	str += "</tr>";
	
	str += "<tr> ";
	str += "<td><span>接班人:</span></td>";
	str += "</tr>";
	
	str += "</table>";
	return str;
}

@Override
public String getSyncObject(SyncObjectContainer so,int mode) {
	PoolMan pm = new PoolMan();
	String message="";
	
	if(mode==1)
	{
		try {
			message= SystemMessage.getMessage(4, 9);
			//pm.Update(so.getSyncobject().add());
			
			//PoolMan pm = new PoolMan();
			  CallableStatement proc = null;
			  proc =  pm.getConnection("test").prepareCall("{call insert_new_row2 (?,?,?)}");
			  proc.setString(1	, "ccode");
			  proc.setString(2	, so.getSyncobject().add());
			  System.out.println(so.getSyncobject().add());
			  proc.registerOutParameter(3,java.sql.Types.INTEGER);  
			  proc.setInt(3, 1);
			  proc.executeUpdate();
			  if(proc.getInt(3)!=0)
			  {
				  message = "未知错误，添加失败";
			  }
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			message ="失败"+e.getMessage();
			e.printStackTrace();
			
		}
	}
	return message;
}

@Override
public Boolean checkhasBcode(String filter) {
	PoolMan pm = new PoolMan();
	String sql = "select count(*) as c from  bcode where "+filter;
	ResultSet rs;
	int count = 0;
	try {
		rs = pm.executeQuery(sql);
		if(rs.next())
		{
			count = rs.getInt("c");
		}
	} catch (Exception e) {
	
		e.printStackTrace();
	}
	return count==1?true:false;
}
/**
 * mode 1 为根据ccode查找 2 为根据name查找 3 为根据phone查找 4 为根据s_cardno查找
 * 检查客户是否存在，录入的密码是否正确
 * 返回true则存在，否则不存在
 * @param code
 * @param mode
 * @return
 */
public boolean checkhasccode(String code,String password,int mode)
{
	String sql ="";
	sql = "select count(*) as c from ";
	sql += "( ";
	if (mode == 2) {
		sql += "select ccode,cname,s_mobil,viplevel,s_cardno from ccode where cname ='"
				+ code + "' and (password='"+password+"' or password is null)";
	} else if (mode == 3) {
		sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where s_mobil ='"
				+ code +"' and (password='"+password+"' or password is null)";
	} else if (mode == 4) {
		sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where s_cardno ='"
				+ code + "' and (password='"+password+"' or password is null)";
	} else {
		sql += "select ccode,cname,s_mobil,viplevel,s_cardno  from ccode where ccode ='"
				+ code + "' and (password='"+password+"' or password is null)";
	}

	sql += ") as a ";
	System.out.println(sql);
	PoolMan pm = new PoolMan();
	ResultSet rs;
	int count = 0;
	try {
		rs = pm.executeQuery(sql);
		if(rs.next())
		{
			count = rs.getInt("c");
		}
	} catch (Exception e) {
	
		e.printStackTrace();
	}
	
	return count==1?true:false;
}
@Override
public Boolean checkhasCcode_scardno(String ccode, String password) {
	PoolMan pm = new PoolMan();
	
	String sql = "select count(*) as c from  ccode where s_cardno='"+ccode +"' and [password] " + (password !=null?" ='"+password +"'" :"is null");
	System.out.println(sql);
	ResultSet rs;
	int count = 0;
	try {
		rs = pm.executeQuery(sql);
		if(rs.next())
		{
			count = rs.getInt("c");
		}
	} catch (Exception e) {
	
		e.printStackTrace();
	}
	
	return count==1?true:false;
}

public Boolean checkhasCcode_scardno_notpass(String ccode) {
	PoolMan pm = new PoolMan();
	
	String sql = "select count(*) as c from  ccode where s_cardno='"+ccode +"'";
	System.out.println(sql);
	ResultSet rs;
	int count = 0;
	try {
		rs = pm.executeQuery(sql);
		if(rs.next())
		{
			count = rs.getInt("c");
		}
	} catch (Exception e) {
	
		e.printStackTrace();
	}
	
	return count==1?true:false;
}
/**
 * 接受客户端的命令组。由于事务死锁，执行sql要放在同一个提交里面执行，任何错误都将所有的事务回滚
 * 不执行后面的sql，对于不是sql的方式暂时不能回滚
 * 2010-2-10 zgw
 */
@Override
	public CommandSyncReturnObject SendCommandSync(CommandSyncContainer comlist) {

		return SendCommandSync(comlist,2);
	}
/**
 * 
 */
@Override
public CommandSyncReturnObject SendCommandSyncSingle(
		CommandSyncContainer comlist) {
	
	return  SendCommandSync(comlist,1);
}
/**
 * 
 * @param mode 1 single 否则多命令模式
 * @return
 */
	private CommandSyncReturnObject SendCommandSync(CommandSyncContainer comlist ,int mode) {
		
		
		
		CommandSyncReturnObject csro = new CommandSyncReturnObject();
		csro.setMessage("");
		if(mode==1)
		{
			if(comlist.getCommandList().size()!=1)
			{
				csro.setMessage("单条命令里出现多条命令。错误！");
				csro.setB(false);
				csro.setRetrunstr(null);
				return csro;
				
			}
		}
		
		PoolMan pm = new PoolMan();
		Connection con=null;
		Statement stmt = null;
		
		try {
			con = pm.getPool("test");
			stmt = con.createStatement();
			
			con.setAutoCommit(false);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		
		for (CommandSync com : comlist.getCommandList()) {
			if (com.getCommandname().equals("EXECSQLLIST")) {

				try {

//					pm.handleTransaction(((CommandSyncsql) com).getV());
					if(((CommandSyncsql) com).isDofirst())
					{
						Connection con2 = null;
						Statement stmt2 =null;
						try{
						 con2 = pm.getPool("test");
						 stmt2 = con2.createStatement();
						for(String str : ((CommandSyncsql) com).getV())
						{
							stmt2.addBatch(str);
						
						}
						stmt2.executeBatch();
						}
						catch (java.sql.BatchUpdateException be)
						{
							if(!com.isContinueorrollback())
							{
								csro.setB(false);
								csro.setMessage(csro.getMessage()+"失败！！！"+be.getMessage());
								break;
							}
						}
						finally
						{
							stmt2.close();
							pm.freeConnection("test", con2);
							
						}
						
				
					}
					else
					{
					for(String str : ((CommandSyncsql) com).getV())
						
						stmt.addBatch(str);
					
					}
//					int i[] = stmt.executeBatch();
//			
//					stmt.clearBatch();
				} 
				catch (java.sql.BatchUpdateException be)
				{
					if(!com.isContinueorrollback())
					{
						csro.setB(false);
						csro.setMessage(csro.getMessage()+"失败！！！"+be.getMessage());
						break;
					}
				
				}
				catch (Exception e) {
					// TODO Auto-generated catch block
					
					e.printStackTrace();
				}
				
			}
			//是否存在改用户
			else if (com.getCommandname().equals("HASCCODE")) {
				String ccode = ((CommandSyncHasCcode) com).getS_cardno();
				String password = ((CommandSyncHasCcode) com).getPassword();
				if(!checkhasCcode_scardno(ccode, password))
				{
					csro.setB(false);
					csro.setMessage(csro.getMessage()+" 会员用户名或密码录入错误");
					//如果设置的是回滚型 则直接退出，无需继续下游命令
					if(!com.isContinueorrollback())
					{
						break;
					}
				}
			}
			else if(com.getCommandname().equals("HASCCODENOTPASS"))
			{
//				checkhasCcode_scardno
				String scardno = ((CommandSyncHasCcodeNotPass) com).getS_cardno();
				if(!checkhasCcode_scardno_notpass(scardno))
				{
					csro.setB(false);
					csro.setMessage(csro.getMessage()+" 会员不存在");
					//如果设置的是回滚型 则直接退出，无需继续下游命令
					if(!com.isContinueorrollback())
					{
						break;
					}
				}
			}
			//用户基本信息
			else if (com.getCommandname().equals("ASSOCIATOR_INFO")) {
				
				String ccode = ((CommandSyncAssociator)com).getCcode();
				int  querymode = ((CommandSyncAssociator)com).getMode();
				double  curpaid = ((CommandSyncAssociator)com).getCurpaid();
				int icode = ((CommandSyncAssociator)com).getIcode();
				Associator associator = getAssociator(ccode,querymode);
				
				if(associator.getFinance()<curpaid)
				{
					csro.setB(false);
					csro.setMessage(csro.getMessage()+" 会员余额不足");
					//如果设置的是回滚型 则直接退出，无需继续下游命令
					if(!com.isContinueorrollback())
					{
						break;
					}
					
				}
				else
				{
					String sql = "update s_service_po set busistatus='131072' ,ccode='"+associator.getCcode()+"' , s_cardno='"+associator.getS_cardno()+"' where icode ='"
									+ icode + "'";
					try {
						stmt.addBatch(sql);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
			
			else if (com.getCommandname().equals("CommandSyncLastStoreg")) {
				
				String icode = ((CommandSyncLastStoreg) com).getIcode();
				String sql = "";
				sql+=" select sum(isnull(a.qty,0)-isnull(b.qty,0)) as qty, cast(sum(isnull(a.qty,0)-isnull(b.qty,0) -isnull(c.qty,0)) as decimal(8,2)) as lastqty ,c.cgicode,c.cgcode,c.gcode,c.qtyunit,c.modeltype from    ";
				sql+=" ( ";
				sql+=" select sum(qty) as qty,cgicode,cgcode,gcode,qtyunit,modeltype from storeslistg   where upicode= '"+icode+"' and inoutflag=3  group by cgicode,cgcode,gcode,qtyunit,modeltype ";
				sql+=" ) as c   ";
				sql+=" left join    ";
				sql+=" ( ";
				sql+=" select sum(qty) as qty,cgicode,cgcode,gcode,qtyunit,modeltype from storeslistg as z1 where inoutflag=2 and exists (select * from storeslistg  as z where upicode= '"+icode+"' and z.cgicode=z1.cgicode and z.cgcode=z1.cgcode and z.gcode=z1.gcode and z.qtyunit = z1.qtyunit ) ";
				sql+="   ";
				sql+=" group by cgicode,cgcode,gcode,qtyunit,modeltype  ";
				sql+=" ) as a   ";
				sql+=" on a.cgicode=c.cgicode and a.cgcode=c.cgcode and a.gcode = c.gcode and a.modeltype = c.modeltype  ";
				sql+="   ";
				sql+="   ";
				sql+=" left join    ";
				sql+=" ( ";
				sql+=" select sum(qty) as qty,cgicode,cgcode,gcode,qtyunit,modeltype from storeslistg as z1 where inoutflag=3 and upicode != '"+icode+"' and exists (select * from storeslistg  as z where upicode= '"+icode+"' and z.cgicode=z1.cgicode and z.cgcode=z1.cgcode and z.gcode=z1.gcode and z.qtyunit = z1.qtyunit )  ";
				sql+=" group by cgicode,cgcode,gcode,qtyunit,modeltype  ";
				sql+=" ) as b   ";
				sql+=" on c.cgicode=b.cgicode and c.cgcode=b.cgcode and c.gcode = b.gcode and a.modeltype = c.modeltype  ";
				sql+=" group by c.cgicode,c.cgcode,c.gcode,c.qtyunit,c.modeltype ";

				try {
					
					ResultSet rs = pm.executeQuery(sql);
					
					while(rs.next())
					{
						if(rs.getDouble("lastqty")<0)
						{
							csro.setB(false);
							csro.setMessage(csro.getMessage()+"\n商品『 barcode:"+rs.getString("cgicode")+" 名称:"+rs.getString("cgcode")+" 规格型号:"+rs.getString("modeltype")+" 类型:"+rs.getString("gcode")+"』 \n剩余数量为"+rs.getString("qty")+"，不足本次使用.提交失败！");
							
						
						
						}
					}
					if(!csro.isB())
					{
						break;
					}
					
					
				} catch (SQLException e) {
					csro.setB(false);
					csro.setMessage(csro.getMessage()+"失败！！！"+e.getMessage());
					e.printStackTrace();
					break;
					
				}
				 catch (Exception e) {
					 csro.setB(false);
					e.printStackTrace(); 
				 }
				
				
			}
			//库存拷贝，入库通知到入库确认
			
			else if (com.getCommandname().equals("_COPYUPSTORELIST")) {
				
				
				
				
				String icode = ((CommandSyncCopyUP) com).getIcode();
				String sql = "";
				sql += "insert into storeslist";
				sql += " (codename,bcode,vprepare,busistatus,modifydate,mark,ccode,busicode,inoutflag,scode,copybusicode,copyicode) ";
				sql += " select  codename,bcode,vprepare,busistatus,modifydate,mark,ccode,busicode,2 as inoutflag,scode,copybusicode,icode ";
				sql += " from storeslist where icode=  '"+icode+"'";
				
			//	String mcolumns="codename,bcode,vprepare,busistatus,modifydate,mark,ccode,busicode,inoutflag,scode";
			//	String gcolumns="idx,codename,ccode,bcode,cgicode,cgcode,gcode,scode,qty,qtyunit,upric,inoutflag,upicode,busicode,modeltype";
			
				String gsql = "";
				gsql +="insert into storeslistg";
				gsql += " (idx,codename,ccode,bcode,cgicode,cgcode,gcode,scode,qty,qtyunit,upric,inoutflag,upicode,busicode,modeltype,buyprice,saleprice )";
				gsql += " select  idx,codename,ccode,bcode,cgicode,cgcode,gcode,scode,qty,qtyunit,upric,2 as inoutflag,IDENT_CURRENT('storeslist') as upicode,busicode,modeltype,buyprice,saleprice  ";
				gsql += " from storeslistg where upicode=  '"+icode+"'";
				
					try {
						
						ResultSet rs = pm.executeQuery("select copyicode from storeslist where copyicode = '"+icode+"'");
						if(rs.next())
							if(rs.getString("copyicode")!=null)
							{
								csro.setB(false);
								csro.setMessage(csro.getMessage()+"此入库已经被确认，提交失败。失败！！！");
								break;
							}
							//System.out.println("copybusicode = "+rs.getString("copybusicode"));
						stmt.addBatch(sql);
						stmt.addBatch(gsql);
					} catch (SQLException e) {
						csro.setB(false);
						csro.setMessage(csro.getMessage()+"失败！！！"+e.getMessage());
						break;
						
					}
					 catch (Exception e) {
						e.printStackTrace(); 
					 }
					//pm.Update(sql);
				
				
				
			
			}
			/**
			 * 收单管理的付款，检查账户余额，
			 */
			else if (com.getCommandname().equals("CommandSyncPay")) {
				
				CommandSyncPay compay = ((CommandSyncPay) com);
				
				if(!checkhasccode(compay.getCcode(),compay.getPassword(),compay.getMode()))
				{
					csro.setB(false);
					csro.setMessage("会员不存在或密码录入不正确\n");
					if(!com.isContinueorrollback())
					break;
				}
				
				List<PayItem> list = compay.getPaylist();
				
				String findsql ="select sqlvalue  from sqltable where name='s_service_pay_item'";

				
				String sql = "";
			
				try {
					ResultSet rs = pm.executeQuery(findsql);
					rs.next();
					sql = rs.getString("sqlvalue");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(list.size()==0)
				{
					csro.setB(false);
					csro.setMessage("未找到账户\n");
					break;
				}
				for(PayItem pi:list)
				{
					
					String scardno=pi.getS_cardno();
					String sqlitem ;
					if(scardno==null)
					{
						sqlitem =sql.replaceAll(Pattern.quote("{SCARDNO}"), " s_cardno='99999999'");
						scardno = "99999999";
					}
					else
					{	
					sqlitem =sql.replaceAll(Pattern.quote("{SCARDNO}"), " s_cardno = '"+scardno+"'");
					}
					sqlitem =sqlitem.replaceAll(Pattern.quote("{ACCCODE}"), pi.getAccountname());
					System.out.println(sqlitem);
					ResultSet rs;
					double lastamount = 0;
					try {
						rs = pm.executeQuery(sqlitem);
						
						
						while(rs.next())
						{
							lastamount = rs.getDouble("lastamount");
						}
						System.out.println("lastamount="+lastamount);
						pi.setLastamount(lastamount);
						//检查账户余额 S开头的账户是系统定义，不检查账户余额
						if (!pi.getAccountname().startsWith("S")) {
							if (pi.isNeedpay()
									&& (lastamount - pi.getPay() - pi
											.getPay_g()) <= -0.01) {
								csro.setB(false);
								csro.setMessage("账户" + pi.getAccountname()
										+ "余额不足\n");
								break;
							}
						}
						if(pi.isNeedpay()&&pi.getUpicode()==null)
						{
							csro.setB(false);
							csro.setMessage("没有注明单据编码\n");
							break;
						}
						//备份旧的付款记录，在单据被修改的情况下，付款记录是不会被删除的，所以在提交的时候备份，然后删除
						String insert_old = "insert into s_service_po_pay_his  (ccode,paid,pay_g,upicode,accountcode) select ccode,paid,pay_g,upicode,accountcode from s_service_po_pay where  upicode = '"+pi.getUpicode()+"'";
						String delete_old = "delete s_service_po_pay where upicode = '"+pi.getUpicode()+"'";
						stmt.addBatch(insert_old);
						stmt.addBatch(delete_old);
						//需要付款则生成付款记录,S开头系统账户不检查余额，否则检查余额，余额足够才付款
						if(!pi.getAccountname().startsWith("S"))
						{
						if(pi.isNeedpay()&&(lastamount-pi.getPay()-pi.getPay_g())>-0.01)
						{
							
							String insertpaysql ="insert into s_service_po_pay (ccode,paid,pay_g,upicode,accountcode)  select top 1 ccode,"+pi.getPay()+","+pi.getPay_g()+","+pi.getUpicode()+",'"+pi.getAccountname()+"' from ccode where s_cardno='"+scardno+"'";
							stmt.addBatch(insertpaysql);
						}
						}
						else
						{
							if(pi.isNeedpay())
							{
							
								String insertpaysql ="insert into s_service_po_pay (ccode,paid,pay_g,upicode,accountcode)  select top 1 ccode,"+pi.getPay()+","+pi.getPay_g()+","+pi.getUpicode()+",'"+pi.getAccountname()+"' from ccode where s_cardno='"+scardno+"'";
								System.out.println("insertpaysql="+insertpaysql);
								stmt.addBatch(insertpaysql);
							}
						}
						
						
					} catch (Exception e) {
						csro.setB(false);
						csro.setMessage("\n"+e.getMessage());
						
						e.printStackTrace();
						break;
					}
					
				}
				
				
			}
			else if (com.getCommandname().equals("_GETMODELDATAS")) {
				CommandSyncGetModelDatas cgmd = ((CommandSyncGetModelDatas) com);
//				String salaryitemmacro = cgmd.getMacro("SALARYITEM");
//				String bcodemacro= cgmd.getMacro("BCODE");
				String sqlname = cgmd.getSqlname();
//				String str = "";
//				str+="                                                                                                       ";
//				str+=" select bcode,no_  as allowanceno_,cast (amount as money) as amount from                                                                                         ";
//				str+=" (                                                                                                     ";
//				str+="                                                                                                       ";
//				str+=" select                                                                                                ";
//				str+=" bcode.bcode,no_ ,desc_cn,amount                                                                        ";
//				str+="                                                                                                       ";
//				str+="  from                                                                                                 ";
//				str+="                                                                                                       ";
//				str+=" (select bcode,bname from bcode                                                                        ";
//				str+=" )                                                                                                     ";
//				str+=" as bcode                                                                                              ";
//				str+=" left join                                                                                             ";
//				str+="                                                                                                       ";
//				str+=" (                                                                                                     ";
//				str+=" select bcode,no_,tactics,desc_cn,amount from bcode_Allowance where no_ not in('A80','A99')            ";
//				str+=" ) as bcode_Allowance                                                                                  ";
//				str+=" on bcode.bcode =bcode_Allowance.bcode                                                                 ";
//				str+="                                                                                                       ";
//				str+="                                                                                                       ";
//				str+="                                                                                                       ";
//				str+=" union all                                                                                             ";
//				str+=" select bcode,'A80' as no_,'失业保险' as desc_cn,socialbase from hr_social_basedetail where            ";
//				str+=" upcode in ( select top  1 icode from hr_social_base where getdate()>adjustdate order by reportdate)  ";
//				str+="                                                                                                      ";
//				str+=" union all                                                                                            ";
//				str+="                                                                                                      ";
//				str+=" select                                                                                               ";
//				str+="  bcode.bcode,no_,desc_cn,                                                                            ";
//				str+=" case                                                                                                 ";
//				str+=" when taxbase>freetax                                                                                 ";
//				str+=" then (taxbase-freetax)*tax-netnum                                                                    ";
//				str+=" else 0                                                                                               ";
//				str+=" end as amount                                                                                        ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+="  from                                                                                                ";
//				str+=" (                                                                                                    ";
//				str+=" select bcode,no_,tactics,desc_cn,amount from bcode_Allowance where no_  in('A99')                    ";
//				str+=" ) as bcode                                                                                           ";
//				str+="                                                                                                      ";
//				str+=" left join                                                                                            ";
//				str+=" (                                                                                                    ";
//				str+="                                                                                                      ";
//				str+=" select sum(amount) as taxbase,bcode                                                                  ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+="  from (                                                                                              ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+=" select                                                                                               ";
//				str+=" bcode.bcode,no_,desc_cn,amount                                                                       ";
//				str+="                                                                                                      ";
//				str+="  from                                                                                                ";
//				str+="                                                                                                      ";
//				str+=" (select bcode,bname from bcode                                                                       ";
//				str+=" )                                                                                                    ";
//				str+=" as bcode                                                                                             ";
//				str+=" left join                                                                                            ";
//				str+="                                                                                                      ";
//				str+=" (                                                                                                    ";
//				str+=" select bcode,no_,tactics,desc_cn,amount from bcode_Allowance where no_ not in('A80','A99')           ";
//				str+=" ) as bcode_Allowance                                                                                 ";
//				str+=" on bcode.bcode =bcode_Allowance.bcode                                                                ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+=" ) as a                                                                                               ";
//				str+="                                                                                                      ";
//				str+=" where exists (select * from hr_salary_item where a.no_=hr_salary_item.code and iftax=1)              ";
//				str+=" group by bcode                                                                                       ";
//				str+=" ) as taxbase                                                                                         ";
//				str+=" on taxbase.bcode = bcode.bcode                                                                       ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+=" left join                                                                                            ";
//				str+="                                                                                                      ";
//				str+=" (                                                                                                    ";
//				str+=" select *,(select taxfree from hr_tax where hr_tax.code=hr_taxdetail.upcode )                         ";
//				str+=" as freetax from hr_taxdetail                                                                         ";
//				str+=" ) as hr_taxdetail                                                                                    ";
//				str+=" on hr_taxdetail.upcode=bcode.tactics                                                                 ";
//				str+="                                                                                                      ";
//				str+=" where  amountstart<taxbase and taxbase<amountend                                                     ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+="                                                                                                      ";
//				str+=" )                                                                                                    ";
//				str+=" as z                                                                                               ";
//				str+=" where bcode in ({BCODE})  and   no_ in ({SALARYITEM} )    order by bcode                                                                   ";
//				
				
				String findsql ="select sqlvalue  from sqltable where name='"+sqlname+"'";
				
				
				
				
//				str =str.replaceAll(Pattern.quote("{SALARYITEM}"), salaryitemmacro);
//				str = str.replaceAll(Pattern.quote("{BCODE}"), bcodemacro);

				
				String sql = "";
			
				try {
					ResultSet rs = pm.executeQuery(findsql);
					rs.next();
					sql = rs.getString("sqlvalue");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				for(String strmarc :cgmd.getHm().keySet())
				{
					sql =sql.replaceAll(Pattern.quote("{"+strmarc+"}"), cgmd.getMacro(strmarc));
				}
				
				StoreInfo si = new StoreInfo();
				System.out.println(sql);
				//Debug.printf(sql);
				si.setSql(sql);
				
				
				ModelDataList  mdl = getModelDataList_Base(si);
				CommandSyncGetModelDatas msgmd = new CommandSyncGetModelDatas();
			msgmd.setList(mdl.getModels());
				
				csro.setCommandsync(msgmd);
			}
			else if(com.getCommandname().equals("_EXESQL"))
			{
				CommandSyncExeSql cgmd = ((CommandSyncExeSql) com);
				
				
				String sqlname = cgmd.getSqlname();
				String findsql ="select sqlvalue  from sqltable where name='"+sqlname+"'";
				String sql = "";
				
				try {
					ResultSet rs = pm.executeQuery(findsql);
					rs.next();
					sql = rs.getString("sqlvalue");
				} catch (Exception e) {
					if(!com.isContinueorrollback())
					{
						csro.setB(false);
						csro.setMessage(csro.getMessage()+"失败！！！"+e.getMessage());
						break;
					}
					e.printStackTrace();
				
				}
				
				try {
					for(String strmarc :cgmd.getHm().keySet())
					{
						sql =sql.replaceAll(Pattern.quote("{"+strmarc+"}"), cgmd.getMacro(strmarc));
					}
					if(pm.Update(sql)==0)
					{
						//没执行到则报错
						if(!com.isContinueorrollback())
						{
							csro.setB(false);
							csro.setMessage(csro.getMessage()+"失败！！！数据没有被更新");
							break;
						}
					}
				} catch (Exception e) {
					if(!com.isContinueorrollback())
					{
						csro.setB(false);
						csro.setMessage(csro.getMessage()+"失败！！！"+e.getMessage());
						break;
					}
					e.printStackTrace();
				}
			
				
			}
			else if (com.getCommandname().equals("MAKECODE")){
				
				String tablename = ((CommandSyncMakeCode) com).getTablename();
				String columnname = ((CommandSyncMakeCode) com).getColumnname();
				String beginstr = ((CommandSyncMakeCode) com).getBeginstr();
				if(tablename==null || columnname==null)
				{
					csro.setB(false);
					csro.setMessage("分配编码未指定表名和字段名！");
					break;
				}
				String code = MakeCode.makeCode(tablename, columnname, beginstr, 5);
				csro.setRetrunstr(code);
			}
			//审批
			else if (com.getCommandname().equals("RATIFY")) {

				CommandSyncRatify comratify = (CommandSyncRatify) com;
				WorkFlow wf = new WorkFlow();

				wf.completetask(comratify.getRatifyinfo().getFlowname(),
						comratify.getRatifyinfo().getBusi(), comratify
								.getRatifyinfo().getIcode(), comratify
								.getRatifyinfo().getUserid(), comratify
								.getRatifyinfo().getId(), comratify
								.getRatifyinfo().getVariables(), comratify
								.getRatifyinfo().getType(), comratify
								.getRatifyinfo().getDescription());

			}
			//启动一个流程
			else if (com.getCommandname().equals("START_FLOW")) {
				CommandSyncStartFlow startflow = (CommandSyncStartFlow) com;
				WorkFlow wf = new WorkFlow();
				String flowname = startflow.getRatifyinfo().getFlowname();
				String busicode= startflow.getRatifyinfo().getBusi();
				String icode = startflow.getRatifyinfo().getIcode();
				
				if(flowname==null)
					flowname = busicode;
				if(wf.findflow(flowname, busicode,icode)!=null)
					{
					csro.setB(false);
						csro.setMessage("你已经进行过提交，请不要重复提交");
						break;
					}
				wf.startflow(flowname, busicode, icode);
				
				
			}
			
			//启动一个流程
			else if (com.getCommandname().equals("COMMANDHTMLTABLE")) {
				CommandHtmlTable startflow = (CommandHtmlTable) com;
				csro.setRetrunstr("");
				
				
			}
			else if (com.getCommandname().equals("PREPARECALL")) {
				
//				暂时不支持返回值，如果失败直接在存储过程里抛出异常
				CommandPrepareCall preparecall = (CommandPrepareCall) com;
				
				String callname = preparecall.getCallname();
				
				List<Item> listitem = preparecall.getItemlist();
				
				int i = 0;
				 CallableStatement proc = null;
				try {
					proc = pm.getConnection("test").prepareCall(
							"{call " + callname + "}");

					for (Item item : listitem) {
						i++;
						if (item.getType()==(CommandPrepareCall.BOOLEAN)) {
							proc.setBoolean(i, Boolean.parseBoolean(item.getValue()));

						} else if (item.getType()==(CommandPrepareCall.TIMESTAMP)) {
							proc.setTimestamp(i, java.sql.Timestamp.valueOf(item.getValue()));
						} else if (item.getType()==(CommandPrepareCall.INT)) {
							proc.setInt(i, Integer.parseInt(item.getValue()));
						} else if (item.getType()==(CommandPrepareCall.LONG)) {
							proc.setLong(i, Long.parseLong(item.getValue()));
						} else if (item.getType()==(CommandPrepareCall.MONEY)) {
							BigDecimal bd = new BigDecimal(item.getValue());
						
							proc.setBigDecimal(i, bd);
						}

						else if (item.getType()==(CommandPrepareCall.STRING)) {
							proc.setString(i, item.getValue());
						} else {
							if (!com.isContinueorrollback()) {
								csro.setB(false);
								csro.setMessage(csro.getMessage() + "失败！！！"
										+ "存储过程：" + callname + "不支持指定的函数类型"
										+ item.getType());
								break;
							}
						}

					}
					
					proc.executeUpdate();
					
					
				} catch (SQLException e) {
					if (!com.isContinueorrollback()) {
						csro.setB(false);
						csro.setMessage(csro.getMessage() + "失败！！！"
								+ e.getMessage());
						break;
					}
				}
				
				csro.setRetrunstr("");
				
				
			}
			
			
			else if (com.getCommandname().equals("BCODEPRESSION")) {
				CommandBcodePermission commandbp = (CommandBcodePermission) com;
			
				String bcode = commandbp.getBcode();
				String password = commandbp.getPassword();
				try {
					ResultSet rs = pm.executeQuery("select count(*) as c from bcode where bcode = '"+bcode+"' and [password]='"+password+"'");
					
					if(rs.next())
					{
						if(rs.getInt("c")!=1)
						{
							if(!com.isContinueorrollback())
							{
							csro.setB(false);
							csro.setMessage("用户名或密码录入不正确！");
							break;
							}
						}
					}
				} catch (Exception e) {
					csro.setB(false);
					csro.setMessage("执行检查用户密码发生异常！");
					
					e.printStackTrace();
					break;
				}
				
				
			}
			
			
			
		}
		
		try {
			int i[] = stmt.executeBatch();
			stmt.clearBatch();
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			csro.setB(false);
			csro.setMessage(csro.getMessage()+"失败！！！"+e2.getMessage());
		}
		
	
		
		try {
			if(csro.isB())
			{
			
			  con.commit();
			
			}
			else
			{
				con.rollback();
			}
			
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		finally
		{
			try {
								con.setAutoCommit(true);
								try {
									pm.close("test");
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return csro;
	}

@Override
public ModelDataList getModelDataList(StoreInfo info,int mode) {
	
	if(mode==1)
	{
		return getModelDataList_Tree(info);
	}
	else if(mode==2)
	{
		return getModelDataList_Base(info);
	}

	return null;
	
}
/**
 * 产生最基本的store
 * @param info
 * @return
 */
public ModelDataList getModelDataList_Base(StoreInfo info) {
	PoolMan pm = new PoolMan();
	
	java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
		ResultSet rs = pm.executeQuery(info.getSql());
		int columncount = rs.getMetaData().getColumnCount();
		String[] column_names = new String[columncount];
		for (int i = 0; i < columncount; i++) {
			column_names[i] = rs.getMetaData().getColumnName(i + 1);
		}
		
		List<BusiObject> list =new ArrayList<BusiObject>();
		int k=0;
		while (rs.next()) {
			
			BusiObject bo = new BusiObject();
			for (int j = 0; j < columncount; j++) {
				//System.out.println(rs.getMetaData().getColumnType(j+1));
				
				if(rs.getMetaData().getColumnType(j+1)==java.sql.Types.TIMESTAMP)
				{
					bo.set(column_names[j], rs.getTimestamp(column_names[j]));
				}
				else if(rs.getMetaData().getColumnType(j+1)==java.sql.Types.BIT)
				{
					bo.set(column_names[j], rs.getBoolean(column_names[j]));
				}
				else if(rs.getMetaData().getColumnType(j+1)==java.sql.Types.DECIMAL)
				{
					bo.set(column_names[j], rs.getDouble(column_names[j]));
				}
				else
				{
					bo.set(column_names[j],  rs.getString(column_names[j]));
			
				
				}
			}
			list.add(bo);
		}
		
		ModelDataList ml = new ModelDataList();
		 ml.setModels(list);
		return ml;
	}
	catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
	
	
	
}
/**
 * 产生treestore
 * @param info
 * @return
 */
public ModelDataList getModelDataList_Tree(StoreInfo info) {
	PoolMan pm = new PoolMan();
	java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
		ResultSet rs = pm.executeQuery(info.getSql());
		int columncount = rs.getMetaData().getColumnCount();
		String[] column_names = new String[columncount];
		for (int i = 0; i < columncount; i++) {
			column_names[i] = rs.getMetaData().getColumnName(i + 1);
		}
		ModelDataList ml = new ModelDataList();
		List<TreeNodeModelData> list =new ArrayList<TreeNodeModelData>();
		ml.setModels(list);
		
		TreeNodeModelData root = new TreeNodeModelData(info);
		root.setNotFlag(info.getTreesortcolumn(), "");
		root.setSortcolumn(info.getTreesortcolumn());
		
		int k=0;
		while (rs.next()) {
			java.util.Map<String, Object> keyoldvalue = new java.util.HashMap<String, Object>();
			
			TreeNodeModelData tnmld = new TreeNodeModelData(info);
			tnmld.setSortcolumn(info.getTreesortcolumn());
			//第一行是root
			if(k==0)
			{
				//root = tnmld;
			}
			
			
			for (int j = 0; j < columncount; j++) {
				
			
				//转换为str
				String datestr;
				//System.out.println(column_names[j]+"--"+rs.getMetaData().getColumnType(j+1));
				//日期
				if(rs.getMetaData().getColumnType(j+1)==java.sql.Types.TIMESTAMP)
				{
					if(rs.getTimestamp(column_names[j])!=null)
					{
					 datestr = sdf.format(rs.getTimestamp(column_names[j]));
					
					 //tnmld.setNotFlagInit(column_names[j], datestr);
					}
					else
					{
						 datestr = null;
						tnmld.setNotFlagInit(column_names[j], null);
						
					}
				}
				
				else if(rs.getMetaData().getColumnType(j+1)==java.sql.Types.BIT)
				{
					if(rs.getBoolean(column_names[j]))
					{
					 datestr = "true";
					
					 //tnmld.setNotFlagInit(column_names[j], datestr);
					}
					else
					{
						 datestr = "false";
						
						
					}
				}
				else
				{
					datestr = rs.getString(column_names[j]);
				//tnmld.setNotFlagInit(column_names[j], rs.getString(column_names[j]));
				}
				tnmld.setNotFlagInit(column_names[j], datestr);
				for(String key:info.getKeyname())
				{
					if(column_names[j].equals(key))
					{
						keyoldvalue.put(key, datestr);
					}
				}
			}
			
			tnmld.setKeyoldvalue(keyoldvalue);
			//if(k!=0)
			{
				root.addNodeSort(tnmld);
			}
			k++;
		}
//		roott.add(root);
		list.add(root);
		return ml;
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}

@Override
public HashMap<String,String> getComet() {
	// TODO Auto-generated method stub
//CometContainer cc=	new CometContainer();
	CometContainer.test();
	return CometContainer.getInstance().ht;
}

@Override
public String getIcode(StoreInfo si, String columnname,String columnvalue) {
	String table = si.getTablename();
	String colname = columnname;
	String colvalue = columnvalue;
	
	int icode =0;
	 PoolMan pm = new PoolMan();
	  CallableStatement proc = null;
	  try {
		proc =  pm.getConnection("test").prepareCall("{call insert_new_row(?,?,?,?)}");
		  proc.setString(1	, table);
		
		 // proc.setInt(2, 1);

		  proc.registerOutParameter(2,java.sql.Types.INTEGER);  
		  proc.setInt(2, 1);
		  proc.setString(3	, colname);
		  proc.setString(4	, colvalue);
		  
		  MyLogger.getInstance().debug("needicode="+" table="+table+" colname ="+colname+" colvalue ="+colvalue);
		  
		  proc.executeUpdate();
		  icode = proc.getInt(2);
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	  
	
	

	return icode+"";
}

/**
 * 
 */
@Override
public AddItem getIcodex(StoreInfo si, String columnname, String columnvalue) {

		String table = si.getTablename();
		String colname = columnname;
		String colvalue = columnvalue;
		AddItem additem = new AddItem();
		int icode = 0;
		PoolMan pm = new PoolMan();
		CallableStatement proc = null;
		try {
			proc = pm.getConnection("test").prepareCall(
					"{call insert_new_rowX(?,?,?,?,?,?,?,?,?)}");
			proc.setString(1, table);
			
			proc.setInt(2, 1);
			proc.registerOutParameter(2, java.sql.Types.INTEGER);
			proc.setString(3, colname);
			proc.setString(4, colvalue);
			proc.setInt(8, 4);//默认长度4
			proc.setString(5, "");
			proc.registerOutParameter(5, java.sql.Types.VARCHAR);
			if(si.getBusiparmas()!=null && si.getBusiparmas().containsKey("CODENAMEPARAMS"))
			{
				String str = si.getBusiparmas().get("CODENAMEPARAMS").toString();
				
				Pattern  pa = Pattern .compile("(\\{)([^\\{\\}]*)(\\})");
				Matcher m = pa.matcher(str);
				StringBuffer sbf = new StringBuffer();
				while(m.find())
				{
					System.out.println("found = "+m.group(2)+" start ="+m.start()+" end="+m.end());
					String bingo = m.group(2);
					if(bingo.startsWith("D"))
					{
						System.out.println("D..");
						String datestr = bingo.substring(2);
						System.out.println(datestr);
						SimpleDateFormat sdf = new SimpleDateFormat(datestr);
						 System.out.println(sdf.format( new Date()));  
						 sbf.append(sdf.format( new Date()));
					}
					else if(bingo.startsWith("INC"))
					{
						System.out.println("INC");
						String incstr = bingo.substring(4);
						proc.setInt(8, Integer.parseInt(incstr));
						sbf.append("INC");
					}
					else
					{
						System.out.println("static");
						sbf.append(bingo);
					}
				}
				
				
				
				
				proc.setString(6, sbf.toString());
			}
			else
			{
				proc.setString(6, "INC");
			}
			if(si.getBusiparmas()!=null &&  si.getBusiparmas().get("CODENAMEFILTER")!=null)
			{
				proc.setString(7, si.getBusiparmas().get("CODENAMEFILTER").toString());
			}
			else
			{
				proc.setString(7, " 1=1");
			}
			
			
			if(si.getBusiparmas()!=null &&  si.getBusiparmas().get("CODENAME")!=null)
			{
				proc.setString(9, si.getBusiparmas().get("CODENAME").toString());
			}
			else
			{
				proc.setString(9, null);
			}
			
			
			
			MyLogger.getInstance().debug(
					"needicode rpc=" + " table=" + table + " colname =" + colname
							+ " colvalue =" + colvalue);

			proc.executeUpdate();
			//icode = proc.getInt(2);
			additem.setIcode(proc.getInt(2)+"");
			additem.setCodename(proc.getString(5));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return additem;

}

public static void main(String[] argv)
{
	GreetingServiceImpl gsi = new GreetingServiceImpl();
	StoreInfo si = new StoreInfo();
	si.setTablename("invoice");
	//HashMap hm = new HashMap();
	si.getBusiparmas().put("CODENAMEPARAMS", "{D:MMdd}{INC:3}{see}");
	si.getBusiparmas().put("CODENAMEFILTER", "1=1");
	AddItem ai =gsi.getIcodex(si,"","");
	System.out.println(ai.getIcode());
	System.out.println(ai.getCodename());
	
	
/*	
	//Pattern  pa = Pattern .compile("\\{[.+[^\\}]]\\}");
//	Pattern  pa = Pattern .compile("(?=\\{[^\\}\\{]*\\})");
	String str = "{D:MMdd}{INC:3}{s}";
	Pattern  pa = Pattern .compile("(\\{)([^\\{\\}]*)(\\})");
	Matcher m = pa.matcher(str);
	StringBuffer sbf = new StringBuffer();
	while(m.find())
	{
		System.out.println("found = "+m.group(2)+" start ="+m.start()+" end="+m.end());
		String bingo = m.group(2);
		if(bingo.startsWith("D"))
		{
			System.out.println("D..");
			String datestr = bingo.substring(2);
			System.out.println(datestr);
			SimpleDateFormat sdf = new SimpleDateFormat(datestr);
			 System.out.println(sdf.format( new Date()));  
			 sbf.append(sdf.format( new Date()));
		}
		else if(bingo.startsWith("INC"))
		{
			System.out.println("INC");
			String incstr = bingo.substring(4);
			
			sbf.append("INC");
		}
		else
		{
			System.out.println("static");
			sbf.append(bingo);
		}
	}
	System.out.println(sbf);*/
	/*try {
		System.out.println(gsi.getMenu().length);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}*/
}

@Override
public String UrlEncode(String str,String c, String enc) {
	// TODO Auto-generated method stub
	try {
		System.out.println(java.net.URLEncoder.encode("中文","GBK"));
		System.out.println(java.net.URLEncoder.encode(new String(str.getBytes(c), enc),enc));
		return java.net.URLEncoder.encode(str,enc);
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
	
}

}
